//
//  WBMainViewController.swift
//  itcastWeibo
//
//  Created by 谢臣 on 2019/10/15.
//  Copyright © 2019 itcast. All rights reserved.
//

import UIKit
//主控制器
class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        // Do any additional setup after loading the view.
    }
    //MARK监听方法
    //@objc即使函数是私有的，也可以保证函数在运行时通过OC的消息机制被调用
    @objc private func composeStatus(){
        print("--------")
    }
    
    //私有控件
    private lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}

//extension 在swift中可以用来切分代码块
//可以把相近功能的函数放在一个extension中，便于代码维护，（）
//设置界面
extension WBMainViewController{
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        //计算按钮的宽度
        let count = children.count
        let w = tabBar.bounds.width / CGFloat(count) - 1 //-1为了让按钮扩大用来挡住两个tabbar按钮的之间的容错点
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    private func setupChildControllers(){
        let array = [
            ["clsName":"WBHomeViewController", "title":"首页", "imageName":"home"],
            ["clsName":"WBMessageViewController", "title":"消息", "imageName":"message_center"],
            ["clsName":"UIViewController"],
            ["clsName":"WBDiscoverViewController", "title":"发现", "imageName":"discover"],
            ["clsName":"WBPrpfileViewController", "title":"我的", "imageName":"profile"],
        ]
        var arrayM = [UIViewController]();
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    //使用字典创建一个子控制器
    //信息字典[clsName,title.imageName]
    private func controller(dict:[String:String]) -> UIViewController{
        //取得字典的内容
        guard let clsName = dict["clsName"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
            else{
                return UIViewController()
        }
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        //设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.orange], for: .highlighted)
        //默认12号字体 要设置Normal的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize:14)], for: UIControl.State(rawValue: 0))
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
